package com.example.shopingcenter.Fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.example.shopingcenter.R;
import com.example.shopingcenter.usercenter.UserCenterLogin;
import com.example.shopingcenter.util.ImageCache;
import com.example.shopingcenter.util.PreferenceManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.StringTokenizer;


public class MineFragment extends Fragment {


    private TextView qianming;
    private TextView nicheng;
    private TextView age;

    private ImageView touxiang;
    private Button btnout;
    private SharedPreferences sp;
    private String input;
    private String input2;
    private EditText changenic;
    private EditText changenic2;
    private SharedPreferences.Editor editor;
    private RadioGroup radioGroup;
    private int code = 0;

    private int selectedYear, selectedMonth, selectedDay;


    private static final int PICK_IMAGE_REQUEST = 1;
    private PreferenceManager preferenceManager;
    private Uri imageUri;
    private Bitmap bitmap;

    private String lastage;
    private String sbitmap ;


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_mine, container, false);


        sp = getActivity().getSharedPreferences("login", getActivity().MODE_PRIVATE);

        editor = sp.edit();


        touxiang = view.findViewById(R.id.imgtouxiang);
        qianming = view.findViewById(R.id.qianmin);
        nicheng = view.findViewById(R.id.nicheng);
        btnout = view.findViewById(R.id.btnout);
        radioGroup = view.findViewById(R.id.radioGroup);
        age = view.findViewById(R.id.age);

        preferenceManager = new PreferenceManager(getContext());

        Log.v("life", "Mine--onCreate");
        Log.v("bitmap2", String.valueOf(bitmap));

        RadioButton radioButton2 = view.findViewById(R.id.radioButton2);


        // 默认选中第一个 RadioButton
        radioButton2.setChecked(true);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = view.findViewById(checkedId);
                if (radioButton != null) {
                    String selectedText = radioButton.getText().toString();
                }
            }
        });


        age.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View view) {

                                       Calendar calendar = Calendar.getInstance();
                                       selectedYear = calendar.get(Calendar.YEAR);
                                       selectedMonth = calendar.get(Calendar.MONTH);
                                       selectedDay = calendar.get(Calendar.DAY_OF_MONTH);

                                       // 创建 DatePickerDialog
                                       DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                                           @Override
                                           public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                               selectedYear = year;
                                               selectedMonth = month;
                                               selectedDay = dayOfMonth;
                                               calculateAge();
                                           }
                                       }, selectedYear, selectedMonth, selectedDay);

                                       // 显示 DatePickerDialog
                                       datePickerDialog.show();
                                   }
                               }

        );


        touxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu = new PopupMenu(getContext(), view);
                Menu menu = popupMenu.getMenu();
                menu.add(Menu.NONE, Menu.FIRST + 1, 1, "拍照");

                menu.add(Menu.NONE, Menu.FIRST + 2, 1, "从相册选取");


                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {

                        switch (menuItem.getItemId()) {

                            case Menu.FIRST + 1:

                                break;
                            case Menu.FIRST + 2:

                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

                                editor.putString("input", nicheng.getText().toString());
                                editor.putString("input2", qianming.getText().toString());
                                editor.putString("age", age.getText().toString());

                                editor.apply();

                                break;
                            default:
                                break;

                        }

                        return false;
                    }
                });

                popupMenu.show();


            }


        });

        btnout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), UserCenterLogin.class);
                startActivity(intent);
            }
        });


        nicheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changenic = view.findViewById(R.id.changenc);
                changenic.setVisibility(View.VISIBLE);
                changenic.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });

                changenic.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View view, int keycode, KeyEvent event) {
                        if (event.getAction() == event.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER) {

                            editor.putString("input", changenic.getText().toString());
                            editor.apply();

                            input = sp.getString("input", "");

                            nicheng.setText(input);
                            changenic.setVisibility(View.GONE);
                            return true;
                        }
                        return false;
                    }
                });
            }
        });

        qianming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changenic2 = view.findViewById(R.id.changenc2);
                changenic2.setVisibility(View.VISIBLE);
                changenic2.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });

                changenic2.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View view, int keycode, KeyEvent event) {
                        if (event.getAction() == event.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER) {

                            editor.putString("input2", changenic2.getText().toString());
                            editor.apply();

                            input2 = sp.getString("input2", "");
                            qianming.setText(input2);
                            changenic2.setVisibility(View.GONE);
                            return true;
                        }
                        return false;
                    }
                });
            }
        });

        return view;
    }


    private void calculateAge() {
        // 获取选择的日期
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.set(selectedYear, selectedMonth, selectedDay);

        // 获取当前日期
        Calendar currentDate = Calendar.getInstance();

        // 计算年龄
        int ages = currentDate.get(Calendar.YEAR) - selectedDate.get(Calendar.YEAR);
        int monthDiff = currentDate.get(Calendar.MONTH) - selectedDate.get(Calendar.MONTH);

        if (monthDiff < 0 || (monthDiff == 0 && currentDate.get(Calendar.DAY_OF_MONTH) < selectedDate.get(Calendar.DAY_OF_MONTH))) {
            ages--;
        }
        editor.putString("age", String.valueOf(ages));
        editor.apply();
        // 显示年龄
        age.setText(String.valueOf(ages));


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
            imageUri = data.getData();
            Log.v("url", String.valueOf(imageUri));

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
                editor.putString("bitmap", bitmapToString(bitmap));
                editor.apply();
                touxiang.setImageBitmap(bitmap);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.v("life", "resume");


        if (preferenceManager.isFirstTimeLogin()) {
            // 如果是第一次访问，启动登录页面

            // 更新状态为已访问
            preferenceManager.setFirstTimeLogin(false);
        } else {
            // 如果不是第一次访问，显示主内容
            // 例如，启动另一个Activity或显示某些UI元素
            input = sp.getString("input", "");
            input2 = sp.getString("input2", "");
            sbitmap = sp.getString("bitmap", "");
            lastage = sp.getString("age", "");


            age.setText(lastage);


            if (sbitmap != null) {

                try {

                    touxiang.setImageBitmap(stringToBitmap(sbitmap));
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }


        }


        if (input != null || input2 != null) {

            qianming.setText(input2);

            nicheng.setText(input);

        }


    }
    public String bitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
    public Bitmap stringToBitmap(String encodedString) {
        byte[] decodedByte = Base64.decode(encodedString, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
    }
}






